package com.heima.comment.service.impl;

import com.heima.apis.user.IUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.pojos.CommentRepayVo;
import com.heima.comment.service.CommentRepayService;
import com.heima.model.comment.dto.CommentRepayDto;
import com.heima.model.comment.dto.CommentRepayLikeDto;
import com.heima.model.comment.dto.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.mongodb.client.result.UpdateResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentRepayServiceImpl implements CommentRepayService {

    private final IUserClient userClient;

    private final MongoTemplate mongoTemplate;
    /**
     * 评论回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length() > 140 ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140个字符");
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }
        //3.安全检查 自行实现

        //4.保存评论
        //获取当前用户信息
        ApUser apUser = userClient.findUserById(user.getId());
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户信息有误");
        }
        //构建评论对象
        ApCommentRepay commentRepay = ApCommentRepay.builder()
                .authorId(user.getId())
                .authorName(apUser.getName())
                .commentId(dto.getCommentId())
                .content(dto.getContent())
                .createdTime(new Date())
                .likes(0)
                .build();
        ApCommentRepay save = mongoTemplate.save(commentRepay);
        if (save.getId() == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"评论回复失败");
        }
        //5更新回复数量
        mongoTemplate.updateFirst(
                Query.query(Criteria.where("id").is(dto.getCommentId())), // 查询条件
                new Update().inc("reply", 1), // 增加reply字段的值
                ApComment.class // 目标文档类型
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论回复点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentRepayId() == null || dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构造查询条件
        Update update = new Update().inc("likes", dto.getOperation() == 0 ? 1 : -1);
        Query query = new Query(Criteria.where("_id").is(dto.getCommentRepayId()));
        //3.点赞
        if (dto.getOperation() == 0){
            //更新评论点赞数量
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ApCommentRepay.class);
            if (updateResult.getModifiedCount() ==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "点赞失败");
            }
            //保存评论点赞数据
            ApCommentRepayLike apCommentRepayLike = ApCommentRepayLike.builder()
                    .commentRepayId(dto.getCommentRepayId())
                    .authorId(user.getId())
                    .build();
            mongoTemplate.save(apCommentRepayLike);
        } else if (dto.getOperation() == 1){
            //更新评论点赞数量
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ApCommentRepay.class);
            if (updateResult.getModifiedCount() ==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "取消点赞失败");
            }
            //删除评论点赞数据
            Query query1 = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId()));
            mongoTemplate.remove(query1);
        }
        //4.返回结果
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        Map<String, Object> result = new HashMap<>();
        if (apCommentRepay != null) {
            result.put("likes", apCommentRepay.getLikes());
        }
        return ResponseResult.okResult(result);
    }
    /**
     * 评论回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int size = Math.min(dto.getSize(), 20);
        //2.加载数据
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("minDate").lt(dto.getMinDate()));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //3.数据封装返回
        //3.1 用户未登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.okResult(apCommentRepays);
        }
        //3.2 用户已登录
        //需要查询当前评论中哪些数据被点赞了
        List<String> idList = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        if (apCommentRepayLikes.isEmpty()){
            return ResponseResult.okResult(apCommentRepays);
        }
        //封装vo
        List<ApCommentRepay> resultList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            CommentRepayVo vo = new CommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay,vo);
            for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                if (apCommentRepayLike.getCommentRepayId().equals(apCommentRepay.getId())){
                    vo.setOperation((short) 0);
                }
            }
            resultList.add(vo);
        }
        return ResponseResult.okResult(resultList);
    }
}
